package com.hjn.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class FileUploaderServlet extends HttpServlet {
    private String filePath;

    @Override
    public void init(ServletConfig config) throws ServletException {
         filePath = config.getInitParameter("filePath");
    }


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)  {
//       表示基于磁盘的fileitem，DiskFileItem 类能将客户端上传的文件保存到磁盘中。
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

//        servletFileUpload 类文件上传处理器，它与FileItemFactory关联。
        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

        try {
            String contentType = req.getContentType();
            String contextPath = req.getContextPath();
            System.out.println("req.getContentLength() = " + req.getContentLength());
            System.out.println(contentType);
            List<FileItem> fileItems = upload.parseRequest(req);
            Iterator<FileItem> iterator = fileItems.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                if (item.isFormField()) {
                    System.out.println("普通表单域，不做处理");
                } else {
                    doUploadFile(req,item);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void doUploadFile(HttpServletRequest request,FileItem item) throws Exception {
        String realPath = request.getServletContext().getRealPath("");
        filePath = realPath + filePath;
        String fieldName = item.getName();
        filePath = filePath + "/" + fieldName;
        //item.write(new File(filePath));
    }
}
